package cn.seaboot.admin.id;

import cn.seaboot.commons.core.StringUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 获取序列的最大值
 * <p>
 * 用于数据校对，避免在强制中断系统时候，产生序列与数据库不一致的情况。
 *
 * @author Mr.css
 * @version 2024-11-21 10:39
 */
public class DefaultMaxValueProvider implements MaxValueProvider {
    /**
     * 数据源
     */
    private DataSource source;
    /**
     * 查询最大值的 SQL
     */
    private String sql;

    public DefaultMaxValueProvider() {
    }

    public DataSource getSource() {
        return source;
    }

    public void setSource(DataSource source) {
        this.source = source;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        sql = sql.trim().toUpperCase();
        if (!sql.startsWith("SELECT")) {
            throw new IllegalArgumentException("illegal query sql:" + sql);
        }
        this.sql = sql;
    }

    /**
     * 查询数据库中，当前的最大值
     *
     * @param tableName 表名
     */
    public void setTableName(String tableName) {
        if (StringUtils.containsWhitespace(tableName)) {
            throw new IllegalArgumentException("illegal table name:" + tableName);
        }
        this.sql = "SELECT MAX(ID) FROM " + tableName;
    }

    /**
     * 获取目前序列的最大值
     *
     * @return id
     */
    public long get() {
        try (Connection conn = source.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {
            if (rs.next()) {
                return rs.getLong(1);
            } else {
                return 0;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
